package com.tang.common.filter;


import com.tang.common.constant.DictConstant;
import com.tang.common.constant.ParamName;
import com.tang.common.utils.cache.DictCache;
import com.tang.common.utils.cache.ParamCache;
import com.tang.module.system.entity.InterfaceConfiguration;
import com.tang.module.system.entity.Role;
import com.tang.module.system.mapper.InterfaceConfigurationMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.ConfigAttribute;
import org.springframework.security.access.SecurityConfig;
import org.springframework.security.web.FilterInvocation;
import org.springframework.security.web.access.intercept.FilterInvocationSecurityMetadataSource;
import org.springframework.stereotype.Component;
import org.springframework.util.AntPathMatcher;

import javax.servlet.http.HttpServletRequest;
import java.util.Collection;
import java.util.List;

/**
 * 权限控制
 * 根据请求url分析所需的角色
 * 放行的url不会通过该类
 * 据库表中的路径需要按照规定设置匹配规则
 * 匹配规则：
 * 1） ?   匹配一个字符（除过操作系统默认的文件分隔符）
 * 2） *   匹配0个或多个字符
 * 3） **  匹配0个或多个目录
 *
 *
 * @author tang
 * @date 2021/4/4 13:45
 */
@Component
public class UrlFilterConfig implements FilterInvocationSecurityMetadataSource {


    @Autowired
    private InterfaceConfigurationMapper interfaceConfigurationMapper;


    private  final AntPathMatcher antPathMatcher = new AntPathMatcher();

    @Override
    public Collection<ConfigAttribute> getAttributes(Object object) throws IllegalArgumentException {
        //获得过滤器
        FilterInvocation filterInvocation = (FilterInvocation) object;
        //获得请求
        HttpServletRequest request = filterInvocation.getRequest();
        //获得url
        String requestUri = request.getRequestURI();
        //获得接口权限对应关系
        List<InterfaceConfiguration> allOrRole = interfaceConfigurationMapper.getAllOrRole();
        for (InterfaceConfiguration interfaceConfiguration : allOrRole) {
            //判断路径和请求方式是否匹配
            if (
                    antPathMatcher.match(interfaceConfiguration.getSign(),requestUri) &&
                     request.getMethod().equals(DictCache.getValue(DictConstant.HTTP_TYPE, Math.toIntExact(interfaceConfiguration.getMethod())))){
                //获取权限名称，转化为数组,放入SecurityConfig
                return SecurityConfig.createList(interfaceConfiguration.getRoleList().stream().map(Role::getRoleName).toArray(String[]::new));
            }

        }
        //没有匹配的url（数据库中未定义的url），默认普通用户可访问
        String defaultRole = ParamCache.getValue(ParamName.DEFAULT_ROLE);
        return SecurityConfig.createList(defaultRole);
    }

    @Override
    public Collection<ConfigAttribute> getAllConfigAttributes() {
        return null;
    }

    @Override
    public boolean supports(Class<?> clazz) {
        return false;
    }
}
